package com.eshopkeeper.service.sys;

import com.baomidou.mybatisplus.plugins.Page;
import com.eshopkeeper.core.support.Assert;
import com.eshopkeeper.core.util.PropertiesUtil;
import com.eshopkeeper.model.sys.SysSession;
import com.eshopkeeper.provider.sys.ISysSessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 
* @Description: 会话
* @author chenshufeng
* @date 2017年3月7日
 */
@Service
public class SysSessionService {
    @Autowired
    private ISysSessionProvider sysSessionProvider;
    @Autowired
    private RedisOperationsSessionRepository sessionRepository;

    public Page<?> query(Map<String, Object> params) {
        String sessiontime= PropertiesUtil.getString("session.maxInactiveInterval");
        params.put("sessiontime",sessiontime);
        return sysSessionProvider.query(params);
    }

    /** 删除会话 */
    public void deleteByAccount(String account, String ownSessionId) {
        Assert.isNotBlank(account, "ACCOUNT");
        List<String> sessionIds = sysSessionProvider.querySessionIdByAccount(account);
        if (sessionIds != null) {
            for (String sessionId : sessionIds) {
                if(!sessionId.equals(ownSessionId)){
                    sysSessionProvider.deleteBySessionId(sessionId);
                    sessionRepository.delete(sessionId);
                    sessionRepository.cleanupExpiredSessions();
                }
            }
        }
    }

    /** 删除会话 */
    public void delete(String account) {
        SysSession sysSession = sysSessionProvider.queryByAccount(account);
        if (sysSession != null) { 
            sysSessionProvider.delete(sysSession.getId());
            sessionRepository.delete(sysSession.getSessionId());
            sessionRepository.cleanupExpiredSessions();
        }
    }

    /** 更新会话 */
    public void update(SysSession record) {
        sysSessionProvider.update(record);
    }

    /** 删除会话 */
    public void deleteBySessionId(String account) {
        SysSession sysSession = sysSessionProvider.queryByAccount(account);
        if (sysSession != null) {
            sysSessionProvider.delete(sysSession.getId());
            sessionRepository.delete(sysSession.getSessionId());
            sessionRepository.cleanupExpiredSessions();
        }
    }

}
